package com.axx.android.letter.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.model.User;
import com.axx.android.moments.MomentActivity;
import com.axx.android.moments.ShowMeAdapter;
import com.axx.android.moments.ShowMeContentActivity;
import com.axx.android.moments.ShowMeModel;
import com.axx.android.profile.kettle.KettleActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageLoader;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecipientActivity extends BaseActivity {


    @Bind(R.id.rv_list)
    RecyclerView rvList;
    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.btn_write_letter)
    Button btnWriteLetter;
    @Bind(R.id.btn_write_showme)
    Button btnWriteShowme;
    @Bind(R.id.layout_refresh)
    SJRefreshView layoutRefresh;
    private User.UserListBean model;

    private int curPage = 1;
    private int pageSize = 10;

    private List<ShowMeModel.ShowMeListBean> list = new ArrayList<>();
    private ShowMeAdapter showMeAdapter;
    private String from;


    @Override
    public int getLayoutId() {
        return R.layout.activity_recipient;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        model = (User.UserListBean) getIntent().getSerializableExtra("model");
        initAdapter();
        from = getIntent().getStringExtra("from");
        if (!TextUtils.isEmpty(from)) {
            btnWriteShowme.setVisibility(View.VISIBLE);
            btnWriteLetter.setVisibility(View.GONE);
        } else {
            if (LetterApp.authUser != null) {
                if (model.getId().equals(LetterApp.authUser.getId())) {
                    btnWriteLetter.setVisibility(View.GONE);
                }
            }
        }

        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchShowMe();
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        layoutRefresh.post(new Runnable() {
            @Override
            public void run() {
                layoutRefresh.setRefreshing(true);
                curPage = 1;
                fetchShowMe();
            }
        });

    }

    private void initAdapter() {
        showMeAdapter = new ShowMeAdapter(R.layout.view_item_show_me, list);
        rvList.setAdapter(showMeAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(this));
        showMeAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchShowMe();
            }
        }, rvList);
        showMeAdapter.addHeaderView(genHeaderView());
        showMeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ShowMeModel.ShowMeListBean list = showMeAdapter.getData().get(position);
                Intent intent = new Intent(RecipientActivity.this, ShowMeContentActivity.class);
                intent.putExtra("model", list);
                intent.putExtra("header", model.getHeadPic());
                startActivity(intent);

            }
        });
    }


    private View genHeaderView() {
        View view = LayoutInflater.from(this).inflate(R.layout.view_header_show_me, (ViewGroup) rvList.getParent(), false);
        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_header);
        ImageView ivBg = (ImageView) view.findViewById(R.id.iv_bg);
        Button btnKettle = (Button) view.findViewById(R.id.btn_kettle);
        btnKettle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecipientActivity.this, KettleActivity.class);
                intent.putExtra("target", model.getId());
                startCheckAuth(intent);
            }
        });

        if (model.getSex().equals("M")) {
            view.findViewById(R.id.view_sex).setBackgroundResource(R.drawable.ic_sex_man);
        }

        tvName.setText(model.getNickName());
        ImageLoader.loadRoundImage(model.getHeadPic(), imageView, this);
        ImageLoader.loadImage(model.getBackPic(), ivBg, this);

        if (LetterApp.authUser != null && LetterApp.authUser.getId().equals(model.getId())) {
            btnKettle.setVisibility(View.GONE);
        }
        return view;
    }

    private void fetchShowMe() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("nowpage", curPage + "");
        hashMap.put("pagenum", pageSize + "");
        hashMap.put("userId", model.getId());
        HttpUtils.post(Constants.Url.ShowMe.SHOW_ME_LIST, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<ShowMeModel> showMeModelBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<ShowMeModel>>() {
                    });
                    if (showMeModelBaseModel.isSuccess()) {
                        showSuccess(showMeModelBaseModel.data.getShowMeList());
                    } else {
                        showToast(showMeModelBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                layoutRefresh.setRefreshing(false);
                showErrorNet();
            }
        });

    }

    private void showSuccess(List<ShowMeModel.ShowMeListBean> showMeList) {
        layoutRefresh.setRefreshing(false);
        if (curPage == 1) {
            if (showMeList.size() == 0) {
                showMeAdapter.addHeaderView(getEmptyView(), 1);
            }
            showMeAdapter.setNewData(showMeList);
            showMeAdapter.disableLoadMoreIfNotFullPage(rvList);
        } else {
            int loadCount = showMeList.size();
            showMeAdapter.addData(showMeList);
            if (loadCount < pageSize) {
                showMeAdapter.loadMoreEnd();
            } else {
                showMeAdapter.loadMoreComplete();
            }
        }
    }

    private View getEmptyView() {
        return LayoutInflater.from(this).inflate(R.layout.view_default_emtpy, (ViewGroup) rvList.getParent(), false);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_write_letter, R.id.btn_write_showme})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_write_letter:
                Intent intent = new Intent(this, LetterWriterActivity.class);
                intent.putExtra("model", model);
                startCheckAuth(intent);
                break;
            case R.id.btn_write_showme:
                startCheckAuth(new Intent(this, MomentActivity.class));
                break;
        }
    }
}
